package com.pospi.xstore.ui.login_ui;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.pospi.xstore.App;
import com.pospi.xstore.R;
import com.pospi.xstore.adapter.CashierLoginAdapter;
import com.pospi.xstore.dao.GoodsDao;
import com.pospi.xstore.dao.ModifiedDao;
import com.pospi.xstore.dao.ModifiedGroupDao;
import com.pospi.xstore.dialog.WaitingDialog;
import com.pospi.xstore.dto.CashierMsgDto;
import com.pospi.xstore.dto.GoodsDto;
import com.pospi.xstore.dto.MenuDto;
import com.pospi.xstore.dto.ModifiedDto;
import com.pospi.xstore.dto.ModifiedGroupDto;
import com.pospi.xstore.dto.ReturnDto;
import com.pospi.xstore.dto.Tablebeen;
import com.pospi.xstore.greendao.TablebeenDao;
import com.pospi.xstore.http.LoadServer;
import com.pospi.xstore.ui.MainActivity;
import com.pospi.xstore.ui.base.BaseActivity;
import com.pospi.xstore.util.Api;
import com.pospi.xstore.util.PareseJson;
import com.pospi.xstore.util.SaveMenuInfo;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class CashierLoginActivity extends BaseActivity {

    @Bind(R.id.lv_cashier)
    ListView lvCashier;

    private CashierLoginAdapter adapter;
    private List<CashierMsgDto> msgDtos;
    private GoodsDao goodsDao;

    private Handler m_handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 22:
                    getMenuData();
                    break;
                case 23:
                    getTableData();
//                   getgroupMsg();
                    break;
                case 24:
                    downMsg();
                    break;
                case 25:
                    downModifiedGroup();
                    break;
                case 26:
//                    downModified();
                    break;

            }
        }
    };
    private Dialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_cashier_login);
        ButterKnife.bind(this);
        tablebeenDao = App.getInstance().getDaoSession().getTablebeenDao();
        setTitle("收银员选择");
        setBackVisible(false);
        showDialog("正在下载商品信息");


        new Thread(new Runnable() {
            @Override
            public void run() {
                Message msg = Message.obtain();
                msg.what = 22;
                m_handler.sendMessage(msg);
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Message msg = Message.obtain();
                msg.what = 23;
                m_handler.sendMessage(msg);
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Message msg = Message.obtain();
                msg.what = 24;
                m_handler.sendMessage(msg);
            }
        }).start();


        new Thread(new Runnable() {
            @Override
            public void run() {
                Message msg = Message.obtain();
                msg.what = 25;
                m_handler.sendMessage(msg);
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Message msg = Message.obtain();
                msg.what = 26;
                m_handler.sendMessage(msg);
            }
        }).start();


        lvCashier.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                inputPwd(position);
            }
        });

    }

    public void showDialog(String msg) {
        if (dialog == null) {
            dialog = WaitingDialog.createLoadingDialog(CashierLoginActivity.this, msg);
            dialog.show();
        }
    }

    public void closeDialog() {
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
    }
    private TablebeenDao tablebeenDao;
    //下载桌子
    public void getTableData() {
        RequestParams params = new RequestParams();//实例化后存入键值对
        LoadServer.getConnect(getApplicationContext(), Api.TABLE, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                if (i == 200) {
                    try {
                        JSONArray object = new JSONArray(new String(bytes));
                        tablebeenDao.deleteAll();
                        for (int j=0;j<object.length();j++) {
                            Tablebeen tablebeen = new Tablebeen();
                            tablebeen.setNumber(object.getJSONObject(j).getString("num"));
                            tablebeen.setStatus(Integer.parseInt(object.getJSONObject(j).getString("status")));
                            tablebeen.setTId(object.getJSONObject(j).getString("id"));
                            tablebeenDao.insert(tablebeen);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });

    }


    /**
     * 进入界面之后联网获取数据下载商品数据库
     */
    public void getMenuData() {

        goodsDao = new GoodsDao(getApplicationContext());

        RequestParams params = new RequestParams();
        params.put("sh_id", getSharedPreferences("StoreMessage", MODE_PRIVATE).getString("Id", ""));

        LoadServer.getConnect(getApplicationContext(), Api.SYNC_MENUS, params, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int code, Header[] headers, byte[] bytes) {
                        if (code == 200) {
                            Log.i("responseBody", new String(bytes));
                            saveGoods(new String(bytes));

                        }
                    }

                    @Override
                    public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

                    }
                }
        );
    }
    private void saveGoods(String response) {
        final List<GoodsDto> dtos = new ArrayList<>();
        final List<MenuDto> menuDtos = new ArrayList<>();
        try {
            JSONObject object = new JSONObject(response);
            JSONArray goodsJson = object.getJSONArray("goods_arrs");
            JSONArray cateJson = object.getJSONArray("goods_cate_arrs");
            for (int i = 0;i<goodsJson.length();i++) {
                GoodsDto dto = new GoodsDto();
                JSONObject data = goodsJson.getJSONObject(i);
                dto.setSid(data.getString("id"));//商品id
                dto.setName(data.getString("goods_name"));//商品名
                dto.setPrice(Double.parseDouble(data.getString("price")));//单价
                dto.setCode(data.getString("barcode"));//商品条码
                dto.setGroup_sid(data.getString("ysz_id"));//样式组
                dto.setImage(data.getString("goods_img"));//图片地址
                dto.setCategory_sid(data.getString("catid"));//分类
                dto.setUnit(data.getString("mode"));//1称重2计数

                dtos.add(dto);
            }
            for (int i=0;i<cateJson.length();i++) {
                MenuDto menuDto = new MenuDto();
                menuDto.setSid(cateJson.getJSONObject(i).getString("id"));
                menuDto.setName(cateJson.getJSONObject(i).getString("cate_name"));
                menuDtos.add(menuDto);
            }
            SaveMenuInfo.saveAsJson(getApplication(), menuDtos);//存储分类

            goodsDao.addGoods(dtos);//存储商品

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    /**
     * 下载做法
     */
    public void downModified() {
        SharedPreferences preferences = getSharedPreferences("StoreMessage", MODE_PRIVATE);
        String shopid = preferences.getString("Id", "");
        RequestParams params = new RequestParams();//实例化后存入键值对
        params.put("value", shopid);
        LoadServer.getConnect(getApplicationContext(), Api.SyncModified, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("SyncModified", new String(bytes));
                try {
                    JSONObject object = new JSONObject(new String(bytes));
                    Gson gson = new Gson();
                    List<ModifiedDto> dtos = gson.fromJson(object.getString("Value"), new TypeToken<List<ModifiedDto>>() {
                    }.getType());
                    new ModifiedDao(getApplicationContext()).addModified(dtos);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });
    }

    /**
     * 下载组
     */
    public void downModifiedGroup() {
        SharedPreferences preferences = getSharedPreferences("StoreMessage", MODE_PRIVATE);
        String shopid = preferences.getString("Id", "");
        RequestParams params = new RequestParams();//实例化后存入键值对
        params.put("sh_id", shopid);
        LoadServer.getConnect(getApplicationContext(), Api.SyncModifiedGroup, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("SyncModifiedGroup", new String(bytes));
                try {
                    JSONObject object = new JSONObject(new String(bytes));
                    saveYSZ(object.getJSONArray("ysz_data"));
                    saveYS(object.getJSONArray("ys_data"));
//                    Gson gson = new Gson();
//                    List<ModifiedGroupDto> dtos = gson.fromJson(object.getString("Value"), new TypeToken<List<ModifiedGroupDto>>() {
//                    }.getType());
//                    new ModifiedGroupDao(MainPospiActivity.this).addModifiedGroup(dtos);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });

    }
    private void saveYSZ(JSONArray ys_data) {
        List<ModifiedGroupDto> groupDtos = new ArrayList<>();
        for (int i = 0; i < ys_data.length(); i++) {
            ModifiedGroupDto dto = new ModifiedGroupDto();
            try {
                dto.setSid(ys_data.getJSONObject(i).getString("id"));
                dto.setName(ys_data.getJSONObject(i).getString("ysz_name"));
                dto.setUid(ys_data.getJSONObject(i).getString("id"));
                dto.setOption_bool(false);
                groupDtos.add(dto);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        new ModifiedGroupDao(this).addModifiedGroup(groupDtos);

    }

    private void saveYS(JSONArray ysz_data) {
        List<ModifiedDto> modifiedDtos = new ArrayList<>();
        for (int i=0;i<ysz_data.length();i++) {
            ModifiedDto modifiedDto = new ModifiedDto();
            try {
                modifiedDto.setSid(ysz_data.getJSONObject(i).getString("id"));
                modifiedDto.setName(ysz_data.getJSONObject(i).getString("ys_name"));
                modifiedDto.setUid(ysz_data.getJSONObject(i).getString("id"));
                modifiedDto.setGroupSid(ysz_data.getJSONObject(i).getString("ysz_id"));
                modifiedDtos.add(modifiedDto);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        new ModifiedDao(this).addModified(modifiedDtos);

    }

    public void getgroupMsg() {
        SharedPreferences preferences = getSharedPreferences("StoreMessage", MODE_PRIVATE);
        String shopid = preferences.getString("Id", "");
        RequestParams params = new RequestParams();
        params.put("value", shopid);
        LoadServer.getConnect(getApplicationContext(), Api.SYNCCATEGORY, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int dd, Header[] headers, byte[] bytes) {
                String response = new String(bytes);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    Log.i("Value", jsonObject.getString("Value"));
                    List<MenuDto> menuDtos = new Gson().fromJson(jsonObject.getString("Value"),
                            new TypeToken<List<MenuDto>>() {
                            }.getType());
                    SaveMenuInfo.saveAsJson(getApplicationContext(), menuDtos);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });
    }


    public void inputPwd(final int position) {

        final EditText editText = new EditText(this);
        editText.setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD);
        editText.setTransformationMethod(PasswordTransformationMethod.getInstance());

        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("收银员账号：" + msgDtos.get(position).getNumber())
                .setMessage("请输入密码:")
                .setView(editText).
                        setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                judgePwd(editText, position);
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
    }


    //收银员登录的时候判断账号密码是否正确
    public void judgePwd(EditText text, int position) {
        if (msgDtos.get(position).getPwd().equals(text.getText().toString())) {
            Toast.makeText(getApplicationContext(), "收银员登录成功", Toast.LENGTH_SHORT).show();
            SharedPreferences.Editor editor = getSharedPreferences("islogin", MODE_PRIVATE).edit();
            editor.putBoolean("islogin", true);
            editor.putInt("which", position);
            editor.apply();


            startActivity(MainActivity.class);
            finish();

        } else {
            Toast.makeText(getApplicationContext(), "密码错误请重新输入！", Toast.LENGTH_SHORT).show();
        }
    }

    public void downMsg() {
        RequestParams params = new RequestParams();
        params.put("sh_id", getSharedPreferences("StoreMessage", MODE_PRIVATE).getString("Id", ""));
        LoadServer.getConnect(getApplicationContext(), Api.SYNCCASHIER, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.d("value", new String(bytes));
                SharedPreferences.Editor editor = getSharedPreferences("cashierMsgDtos", MODE_PRIVATE).edit();
                editor.putString("cashierMsgDtos", new String(bytes));
                editor.apply();
                msgDtos = new PareseJson().parese(new String(bytes));
                adapter = new CashierLoginAdapter(getApplicationContext(), msgDtos);
                lvCashier.setAdapter(adapter);
                closeDialog();
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                showToast("加载失败，请稍后重试");
            }
        });
    }


}
